package net.javastone.toolkit.joinfile;

import net.javastone.toolkit.core.utils.Args;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileJoin {

  private static final String FILTER_PREFIX = "prefix:";

  private static final String FILTER_SUFFIX = "suffix:";

  public static void main(String[] args) {
    joinFiles(getSourceDir(args), getFilter(args), new File(getDestDir(args)), getEncoding(args));
  }

  /**
   * 编码
   *
   * @param args
   * @return
   */
  private static String getEncoding(String[] args) {
    return Args.getParameter(args, 3).orElse("UTF-8");

  }

  /**
   * 过滤器
   *
   * @param args
   * @return
   */
  private static FileFilter getFilter(String[] args) {
    FileFilter filter = null;
    String filterStr = Args.getParameter(args, 2).orElse(null);
    if (filterStr != null) {
      if (filterStr.startsWith(FILTER_PREFIX)) {//前匹配
        filter = new PrefixFileFilter(filterStr.substring(FILTER_PREFIX.length()));
      } else if (filterStr.startsWith(FILTER_SUFFIX)) {//后匹配
        filter = new SuffixFileFilter(filterStr.substring(FILTER_PREFIX.length()));
      } else {//正则匹配
        filter = new RegexFileFilter(filterStr);
      }
    }
    return filter;
  }

  /**
   * 目标文件
   *
   * @param args
   * @return
   */
  private static String getDestDir(String[] args) {
    return Args.getParameter(args, 1).orElseThrow(() -> new RuntimeException("请指定目标文件"));
  }

  /**
   * 来源文件夹
   *
   * @param args
   * @return
   */
  private static String getSourceDir(String[] args) {
    return Args.getParameter(args, 0).orElseThrow(() -> new RuntimeException("请指定来源文件夹"));
  }

  /**
   * 合并逻辑
   *
   * @param dirPath
   * @param filter
   * @param dest
   * @param encoding
   */
  private static void joinFiles(String dirPath, FileFilter filter, File dest, String encoding) {
    File dir = new File(dirPath);
    if (dir == null || !dir.isDirectory()) {
      throw new RuntimeException(dirPath + "文件夹不存在");
    }
    try {
      FileOutputStream fos = new FileOutputStream(dest);
      for (File file : dir.listFiles(filter)) {
        if (file.isDirectory()) {
          continue;
        }
        FileInputStream fis = new FileInputStream(file);
        IOUtils.writeLines(IOUtils.readLines(fis, encoding), "\n", fos, encoding);
        fis.close();
      }
      fos.flush();
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}